<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;


class ActivityModel extends  Model{

	protected $table='game_activity';
    protected $_db_select = 'mysql';

    public $timestamps = false;
    //public $incrementing = false;
    // protected $primaryKey = "id";

    //const UPDATED_AT = NULL;
    // const CREATED_AT = NULL;

    const DB_FIELDS = 'id,act_id,area,act_name,act_type,act_object,cond,item_list,create_time,send_time';   

    public function selectdb(){
        if ($select) {
            return $this->_db_select = $select;
        }
        return $this->_db_select;
    }
    public function getConnectionName(){
        return $this->selectdb();
    }
    public static function with($relations)
    {
        return new static;
    }
    public function paginate()
    {
    	$perPage = Request::get('per_page', 20);

        $page = Request::get('page', 1);
        $act_type = Request::get('event_id', 201);
        
        $start = ($page-1)*$perPage;

        $rw = \DB::connection($this->selectdb())->table($this->table)->where('act_type', $act_type)->orderBy("id", "desc")->skip($start)->take($perPage);
        self::SourceCondition($rw);
        $data = $rw->get();
        $data = $data->toArray();

        $send_obj = new self();
        $send_obj->area = Request::get('area');
        $send_obj->act_type =  $act_type;
        $active_acts = self::syncToGame($send_obj, Request::get('area'), 'get_ids') ?: [];

        foreach ($data as &$obj) {

            $obj->act_object = empty($obj->act_object) ? [] : json_decode($obj->act_object, true);
            $obj->item_list = empty($obj->item_list) ? [] : json_decode($obj->item_list, true);
            $obj->active = in_array($obj->act_id, $active_acts) ? 1: 0;
        }

        $total = \DB::connection($this->selectdb())->table($this->table)->where('deleted_at', 0)->count();

        // $data = json_decode($data, true);
        \Log::debug(__METHOD__, [$rw->toSql()]);
        $list = static::hydrate($data);

        $paginator = new LengthAwarePaginator($list, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }    

    public static function SourceCondition(&$rw)
    {
        $cond = Request::all();
        if ($cond['act_name']){
            $rw->where("act_name", 'like', $cond["act_name"].'%');
        }
        if ($cond['act_id']){
            $rw->where("act_id", $cond["act_id"]);
        }
        if ($cond["area"] or $cond['area']){
            $rw->where("area", $cond['area'] ?: $cond['area']);
        }

    }
    public static function assignByOut(&$one, $out){
        $flds = explode(',', self::DB_FIELDS);
        
        self::conv_2_object($one);
        
        !is_array($out['item_list']) && $out['item_list'] = json_decode($out['item_list'], true);
        !is_array($out['act_object']) && $out['act_object'] = json_decode($out['act_object'], true);

        
        // 这几判定没有邮件会发送不成功
        if (!$out['act_object']) {
            return -4408;
        }
        if (!$out['act_object']['title'] || !$out['act_object']['content']) {
            return -4409;
        }       
        foreach ($flds as $fld) {
            $fld = trim($fld);
            isset($out[$fld]) && $one->{$fld} = $out[$fld];
            if (in_array($fld, ['item_list', 'act_object'])){
                if (is_string($one->{$fld})) {
                    $one->{$fld} = json_decode($one->{$fld}, true);
                }
                
                if ( $fld == 'item_list' && is_array($one->{$fld}) ){
                    $one->{$fld} = array_values($one->{$fld});
                    $one->{$fld} = json_encode($one->{$fld}, JSON_UNESCAPED_UNICODE);
                }

                if (is_array($one->{$fld})){
                    $one->{$fld} = (json_encode($one->{$fld}, JSON_UNESCAPED_UNICODE));
                }
            }
        }
        return 0;
    }

    public static function conv_2_object($one) {
        if (is_string($one->act_object)) {
            $one->act_object = json_decode($one->act_object, true);
        }
        $one->act_object = $one->act_object ?:[];

        if ( is_string($one->item_list) ) {
            $one->item_list = json_decode($one->item_list, true);
        }
        $one->item_list = $one->item_list ?:[];
    }
    // 事件类型列表
    public static function getEventList() {
        return [
            201 => [
                201,                    // 事件id
                'Create Player Email',  // 事件名称
                1
            ],
            202 => [
                202,
                'Undefined',
                0
            ],
        ];
    }

    public static function getEventListOption(){
        $data = self::getEventList();
        $rtn = [] ;
        foreach ( $data as $obj ) {
            $rtn[$obj[0]] = $obj[1];
        }

        return $rtn;
    }

    // 同步消息到game
    protected static function syncToGame($one, $area, $operator){
        if (empty($one) || empty($area) || empty($operator)) {
            \Log::debug(__METHOD__. ' sync activity to game param error', ['area'=> $area, 'operator' => $operator]);
            return ;
        }
        self::conv_2_object($one);
        \App\Models\SendSocketToGame::SendAction(function($socket)use(&$result, $one, $operator, $area){
            $data['msgid'] = $msgid ?:  \App\Service\MessageDef::http_plat_game_request;
            $data["area"] = $area ? intval($area) : \App\Models\Area::getPhysicsArea($one->area); 
            $data['game_msgid'] = \App\Service\MessageDef::http_plat_sync_activity_request;
            $data["playerId"] = 1;

            $act_data = [
                'act_object' => $one->act_object,
                'item_list'  => $one->item_list,
                'act_id'     => $one->act_id,
                'act_type'   => $one->act_type,
            ];
            $data["game_msg"] = [  
                'act_type'  => $one->act_type,
                'act_id'    => $one->act_id,
                'operator'  => $operator,
                'act_data'  => json_encode($act_data, JSON_UNESCAPED_UNICODE),
            ];
            $ret = $socket->send($data);
            $result = $socket->ReadHttpReponse() ?: [];
            \Log::debug('activity sync game response', [$ret, $result]);
        });

        return $result['data'];
    }
}